package com.le.tester.imooc.masterJUC.lock.atomic;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 描述：将一个普通的integer升级成原子类型
 */
public class AtomicIntegerFieldUpdaterDemo implements Runnable {

    static Candidate tom;
    static Candidate peter;

    public static AtomicIntegerFieldUpdater<Candidate> integerFieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");

    public static void main(String[] args) throws InterruptedException {
        tom = new Candidate();
        peter = new Candidate();

        AtomicIntegerFieldUpdaterDemo atomicIntegerFieldUpdater = new AtomicIntegerFieldUpdaterDemo();
        Thread thread1 = new Thread(atomicIntegerFieldUpdater);
        Thread thread2 = new Thread(atomicIntegerFieldUpdater);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("peter score is " + peter.score);
        System.out.println("tom score is " + tom.score);
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            peter.score++;
            integerFieldUpdater.getAndIncrement(tom);
        }
    }

    public static class Candidate {
        //有可见性，并没有原子性
        //变量是不支持静态的
        volatile int score;
    }
}
